package yaohua.main;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import yaohua.entity.Entity_help;
import yaohua.jsoup.Jsoup_help;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

/**
 * 检索到的书目列表界面
 * 
 * @author yh
 * 
 */
public class SearchBooksActivity extends ListActivity
	{

		public static final String SEARCH = "http://202.207.182.100:8080/pft/wxjs/tmjs.asp";
		private String language;// 中文或英文
		private String searchWay;// 检索方式
		private String keyWord;// 关键词
		private String type = "%";// 题名类型
		private String queryWay;// 查询方式
		private String max = "0";
		private String records = "20";
		private String order = "正题名";

		private String language_name = "txtWxlx";
		private String searchWay_name = "txtPY";
		private String keyWord_name = "txtTm";
		private String type_name = "txtLx";
		private String queryWay_name = "txtSearchType";
		private String max_name = "nMaxCount";
		private String records_name = "nSetPageSize";
		private String order_name = "cSortFld";

		ProgressDialog progressDialog;
		SimpleAdapter sa;
		ArrayList<String> dateList;
		//ArrayList<String> books;
		ArrayList newBooks;
		ArrayList<String> storeUrl;
		String result;
		int maxPage;
		int pageNumber = 2;

		private Button more;

		@Override
		protected void onCreate(Bundle savedInstanceState)
			{
				super.onCreate(savedInstanceState);
				// 设置无标题
				requestWindowFeature(Window.FEATURE_NO_TITLE);
				setContentView(R.layout.searchbooks);
				// 从intent获取数据
				Intent intent = getIntent();
				dateList = intent.getStringArrayListExtra("dateList");
				//books = intent.getStringArrayListExtra("books");
				newBooks=intent.getParcelableArrayListExtra("newBooks");
				result = intent.getStringExtra("result");
				language = intent.getStringExtra("language");
				searchWay = intent.getStringExtra("searchWay");
				keyWord = intent.getStringExtra("keyWord");
				queryWay = intent.getStringExtra("queryWay");
				storeUrl = intent.getStringArrayListExtra("storeUrl");
				// 初始化界面
				 sa = new SimpleAdapter(this, newBooks, android.R.layout.simple_list_item_2, new String[]
					{ "title", "value" }, new int[]
					{ android.R.id.text1, android.R.id.text2 });
				this.setListAdapter(sa);

				// 获得组件
				more = (Button) findViewById(R.id.more);
				more.setOnClickListener(new MoreListener());
				// 获得总页数(-1其实是为了120行代码处的，因为这里第一页已经翻出去了，所以总页数-1了)
				maxPage = getMaxPage(result) - 1;

			}

		@Override
		public boolean onOptionsItemSelected(MenuItem item)
			{
				new AlertDialog.Builder(this).setTitle("关于").setMessage("本程序为中北大学图书馆使用,欢迎您能向作者提供在使用过程中的bug,以方便作者进行修改.联系作者新浪微薄@耀华info")
						.show();
				return super.onOptionsItemSelected(item);
			}

		@Override
		public boolean onCreateOptionsMenu(Menu menu)
			{
				menu.add("关于");
				return super.onCreateOptionsMenu(menu);
			}

		/**
		 * ItemClick监听代码
		 */
		@Override
		protected void onListItemClick(ListView l, View v, int position, long id)
			{
				super.onListItemClick(l, v, position, id);
				new Jsoup_help().handlerItem(result, "tdborder2", 6, position, (ArrayList<String>) dateList, storeUrl, (Context) this,
						SearchItemActivity.class);
			}

		/**
		 * 更多按钮监听代码
		 * 
		 * @author yh
		 * 
		 */

		class MoreListener implements OnClickListener
			{

				public void onClick(View v)
					{
						progressDialog = ProgressDialog.show(SearchBooksActivity.this, "正在查询", "请稍等...", false, true);
						new Thread(new Runnable()
							{

								public void run()
									{
										try
											{
												if (maxPage > 0)// 测试是否到达最后一页
													{
														String nextUrl = getNextUrl();
														maxPage--;
														Entity_help entity_help = new Entity_help();
														HttpResponse httpResponse = entity_help.getResponse(nextUrl);
														// 没有网络的话，此处httpResponse==null
														if (httpResponse == null)
															{
																Message msg = new Message();
																msg.arg1 = -1;
																handler.sendMessage(msg);
															}
														// 服务器错误
														if (!entity_help.code200(httpResponse))
															{
																Message msg = new Message();
																msg.arg1 = -2;
																handler.sendMessage(msg);
															}
														entity_help.handleBook(httpResponse, handler, "tdborder4", 1, 6,2,6,
																progressDialog);
													}
												else
													{
														Message msg = new Message();
														msg.arg1 = 1;
														handler.sendMessage(msg);

													}
											}
										catch (Exception e)
											{
												e.printStackTrace();
											}
										finally
											{
												progressDialog.dismiss();
											}
									}

							}).start();

					}

				private Handler handler = new Handler()
					{

						@Override
						public void handleMessage(Message msg)
							{
								super.handleMessage(msg);
								if (msg.arg1 == -1)
									{
										msg.arg1 = 0;
										progressDialog.dismiss();
										Toast.makeText(getApplicationContext(), "网络连接不可用，请检查网络设置", Toast.LENGTH_SHORT).show();
									}
								else if (msg.arg1 == 1)
									{
										msg.arg1 = 0;
										progressDialog.dismiss();
										Toast.makeText(getApplicationContext(), "已经到最后一页了", Toast.LENGTH_SHORT).show();
									}
								else if(msg.arg1==-2)
									{
										progressDialog.dismiss();
										Toast.makeText(getApplicationContext(), "内部服务器错误", Toast.LENGTH_SHORT).show();
										msg.arg1 = 0;
									}
								else
									{
										Bundle bundle = msg.getData();
										ArrayList<String> dateList_new = bundle.getStringArrayList("list");
										//ArrayList<String> books_new = bundle.getStringArrayList("books");
										ArrayList newBooks_new=bundle.getParcelableArrayList("newBooks");
										ArrayList<String> storeUrl_new = bundle.getStringArrayList("storeUrl");

										dateList.addAll(dateList_new);
										//books.addAll(books_new);
										newBooks.addAll(newBooks_new);
										storeUrl.addAll(storeUrl_new);
										sa.notifyDataSetChanged();
										Toast.makeText(getApplicationContext(), "还剩下" + maxPage + "页", Toast.LENGTH_SHORT).show();
									}
							}

					};

			}

		/**
		 * 生成翻页url
		 * 
		 * @throws UnsupportedEncodingException
		 */
		public String getNextUrl() throws UnsupportedEncodingException
			{

				String nextUrl = SEARCH + "?page=" + pageNumber + "&" + language_name + "=" + language + "&" + keyWord_name + "="
						+ java.net.URLEncoder.encode(keyWord, "GBK") + "&" + type_name + "=" + java.net.URLEncoder.encode(type) + "&"
						+ queryWay_name + "=" + queryWay + "&" + max_name + "=" + max + "&" + records_name + "=" + records + "&"
						+ searchWay_name + "=" + searchWay + "&" + order_name + "=" + java.net.URLEncoder.encode(order);
				pageNumber++;
				return nextUrl;
			}

		/**
		 * 通过正则表达式获得页面的总数
		 */
		public int getMaxPage(String result)
			{
				Pattern pattern = Pattern.compile("</font>/(\\d+)");
				Matcher regexMatcher = pattern.matcher(result);
				if (regexMatcher.find())
					{
						String s = regexMatcher.group(1);
						maxPage = Integer.parseInt(s);

					}
				return maxPage;
			}

	}
